# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

DevSetting_fields = ['DEBUG', 'ALLOWED_HOSTS', 'WL_THEME', 'CACHE_MIDDLEWARE_SECONDS', 'CACHE_MIDDLEWARE_KEY_PREFIX',
                     'FILE_UPLOAD_MAX_MEMORY_SIZE', 'EMAIL_HOST', 'EMAIL_PORT', 'EMAIL_HOST_USER',
                     'EMAIL_HOST_PASSWORD', 'SM_ACCOUNTSID', 'SM_ACCOUNTTOKEN', 'SM_APPID',
                     'SM_SERVERIP', 'SM_SERVERPORT', 'SM_SOFTVERSION']


# 开发者选项
class DevSetting(models.Model):
    DEBUG = models.CharField('是否启用调试', max_length=5, null=True, default="True", choices=(("False", "否"), ("True", "是")),
                             help_text="打开调试时，如有代码引起的程序错误，则会在前端显示django的错误调试页面，方便开发查找错误。<br>注意：打开调试也会暴露服务器配置等信息，线上生产环境请务必关闭。")
    ALLOWED_HOSTS = models.CharField('授权的域名', max_length=200, null=True, default="wenlincms.com",
                                     help_text="可多个，用','分隔。若调试打开，该设置无效。")
    WL_THEME = models.CharField('启用的主题', max_length=50, null=True, default="wltheme",
                                help_text="请填写主题在template目录下的文件夹名称，默认为wltheme。<br>若主题目录不存在或系统所需的html文件在主题目录中不存在，都会使用wltheme中的相应文件")
    CACHE_MIDDLEWARE_SECONDS = models.IntegerField("缓存时间", default=900, null=True,
                                                   help_text="全站缓存的默认时间，单位：秒")
    CACHE_MIDDLEWARE_KEY_PREFIX = models.CharField("缓存前缀", max_length=20, null=True, default="wenlincms",
                                                   help_text="缓存文件的前缀，用于区分。请填写一个3-8位的字符串")
    FILE_UPLOAD_MAX_MEMORY_SIZE = models.IntegerField('文件上传大小上限', default=8388608, null=True,
                                                      help_text='设置最大允许上传的文件大小，单位：bit。8388608=8M')
    EMAIL_HOST = models.CharField('SMTP服务器', max_length=75, blank=True, null=True, default="smtp.163.com",
                                  help_text="邮件发送服务器地址，比如：smtp.ym.163.com")
    EMAIL_PORT = models.IntegerField('端口号', null=True, blank=True, default="25", help_text="一般为25")
    EMAIL_HOST_USER = models.CharField("账号", blank=True, null=True, max_length=100, default="")
    EMAIL_HOST_PASSWORD = models.CharField('密码', blank=True, null=True, max_length=100, default="")
    SM_ACCOUNTSID = models.CharField('短信服务账号', max_length=100, null=True, blank=True, default="",
                                     help_text="填写短信云服务的账号等信息，用于发送注册时的验证码等。若第一次使用，推荐使用容联短信服务：<a href='http://www.yuntongxun.com/' target='_blank'>点击申请</a>")
    SM_ACCOUNTTOKEN = models.CharField('服务token', max_length=100, null=True, blank=True, default="")
    SM_APPID = models.CharField('应用Id', max_length=100, null=True, blank=True, default="")
    SM_SERVERIP = models.CharField('服务地址', max_length=50, null=True, blank=True, default="",
                                   help_text="请求地址，不需要写http://")
    SM_SERVERPORT = models.IntegerField('端口', null=True, blank=True, default=25)
    SM_SOFTVERSION = models.CharField('版本', max_length=30, null=True, blank=True, default="")

    class Meta:
        verbose_name = '开发者选项'
        verbose_name_plural = '开发者选项'
        db_table = 'conf_dev'

    def __unicode__(self):
        return u'开发者选项'

    def save(self, *args, **kwargs):
        if self.id:
            DevSetting.objects.exclude(id=self.id).delete()

        # 保存配置数据到config.py
        allowed_host_trans = ""
        for s in self.ALLOWED_HOSTS.split(","):
            allowed_host_trans += '"' + s.strip() + '", '
        the_theme = self.WL_THEME.strip() if self.WL_THEME.strip() else "wltheme"

        # config.py样本
        config_text = """# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals

# 本文件记录可在后台动态配置的一些设置，如需添加其他django设置，请修改settings.py

# 是否开启调试
DEBUG = %s

# 允许链接的域名
ALLOWED_HOSTS = [%s]

# 启用的主题
WL_THEME = "%s"

# 全站缓存时间
CACHE_MIDDLEWARE_SECONDS = %s
# 缓存前缀
CACHE_MIDDLEWARE_KEY_PREFIX = "%s"

# 文件最大上传大小
FILE_UPLOAD_MAX_MEMORY_SIZE = %s  # 默认值

# 邮件服务器相关设置
EMAIL_HOST = '%s'
EMAIL_PORT = %s
EMAIL_HOST_USER = '%s'
EMAIL_HOST_PASSWORD = '%s'

# 邮件发送选项
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

# 短信服务接口
SM_OPTIONS = {
    'ACCOUNTSID': '%s',
    'ACCOUNTTOKEN': '%s',
    'APPID': '%s',
    'SERVERIP': '%s',
    'SERVERPORT': %s,
    'SOFTVERSION': '%s'
}
""" % (self.DEBUG, allowed_host_trans, the_theme, self.CACHE_MIDDLEWARE_SECONDS, self.CACHE_MIDDLEWARE_KEY_PREFIX,
       self.FILE_UPLOAD_MAX_MEMORY_SIZE, self.EMAIL_HOST.strip(), self.EMAIL_PORT, self.EMAIL_HOST_USER.strip(),
       self.EMAIL_HOST_PASSWORD.strip(), self.SM_ACCOUNTSID.strip(), self.SM_ACCOUNTTOKEN.strip(),
       self.SM_APPID.strip(), self.SM_SERVERIP.strip(), self.SM_SERVERPORT,
       self.SM_SOFTVERSION.strip())

        config_file = open('mainsys/config.py', 'w')
        config_file.write(config_text.encode("utf-8"))
        config_file.close()
        super(DevSetting, self).save(*args, **kwargs)
        # 重新加载代码
        try:
            import uwsgi
            from wlapps.utils import code_changed
            if code_changed():
                uwsgi.reload()
        except Exception:
            pass
